package cz.incad.psh.pshassign.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import cz.incad.psh.pshassign.client.json.ResultDoc;
import cz.incad.psh.pshassign.client.json.SearchData;
import cz.incad.psh.pshassign.client.rpc.PSHService;
import cz.incad.psh.pshassign.client.rpc.PSHServiceAsync;

/**
 *
 * @author Alberto Hernandez
 */
public class InvenioSearch extends Composite implements RequiresResize {

    private static invenioSearchUiBinder uiBinder = GWT.create(invenioSearchUiBinder.class);
    PSHServiceAsync pshService = GWT.create(PSHService.class);
    @UiField
    TextBox q;
    @UiField
    Anchor search;
    @UiField
    ScrollPanel scrollPanel = new ScrollPanel();
    @UiField
    FlowPanel header;
    @UiField
    FlowPanel resultsPanel;
    @UiField
    HTMLPanel content;
    @UiField
    Image loading;

    @Override
    public void onResize() {
        scrollPanel.setPixelSize(content.getOffsetWidth(),
                        content.getOffsetHeight() - header.getOffsetHeight());
    }

    interface invenioSearchUiBinder extends UiBinder<Widget, InvenioSearch> {
    }

    public InvenioSearch() {
        initWidget(uiBinder.createAndBindUi(this));
        search.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                MainPage mainPage = (MainPage) RootLayoutPanel.get().getWidget(0);
                mainPage.clearPSHKeys();
                doSearch();
            }
        });

        q.addKeyPressHandler(new KeyPressHandler() {
            @Override
            public void onKeyPress(KeyPressEvent event) {
                boolean enterPressed = KeyCodes.KEY_ENTER == event.getNativeEvent().getKeyCode();
                if (enterPressed) {
                    MainPage mainPage = (MainPage) RootLayoutPanel.get().getWidget(0);
                    mainPage.clearPSHKeys();
                    doSearch();
                }
            }
        });
        String qp = Window.Location.getParameter("id");
        if(qp !=null){
            q.setText("id:" +qp);
            doSearch();
        }else{
            qp = Window.Location.getParameter("q");
            if(qp !=null){
                q.setText(qp);
            }
            doSearch();
        }
    }

    private void doSearch() {
        resultsPanel.clear();
        loading.setVisible(true);
        String query;

        String sort = "";
        if (q.getText() == null || q.getText().trim().length() == 0) {
            query = "*:*";
            sort = "&sort=title+asc";
        } else if(q.getText().contains(":")) {
            query = q.getText();
        }else {
            query = q.getText() + " title:(" + q.getText() + ")^2";
        }
        //query = query.replaceAll(" ", "+");

        pshService.searchNusl(query, new AsyncCallback() {
            @Override
            public void onFailure(Throwable caught) {
                loading.setVisible(false);
                resultsPanel.add(new InlineHTML("error searching nusl:"
                        + caught.getLocalizedMessage()));
            }

            @Override
            public void onSuccess(Object result) {
//                resultsPanel.add(new InlineHTML((String) result));
                JSONObject json = JSONParser.parseStrict((String) result).isObject();
                if(json.containsKey("error")){
                    resultsPanel.add(new InlineHTML("error searching nusl: <br/>"
                        + json.get("error").toString()));
                }else{
                    SearchData js = SearchData.parseJson((String) result);
                    resultsPanel.add(new InlineHTML("num docs: " + Integer.toString(js.getNumDocs())));
                    JsArray<ResultDoc> docs = js.getResults();
                    for (int i = 0; i < docs.length(); i++) {
                        final ResultDoc doc = docs.get(i);
                        ResultBox rb = new ResultBox(doc);
                        resultsPanel.add(rb);
                    }

                    onResize();
                }
                loading.setVisible(false);
            }
        });

    }
}
